﻿#region Using Directives

using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TeamArchitect.PowerTools.Features;

#endregion

namespace FeatureBuilder.Contrib.Commands
{
    /// <summary>
    /// Feature Extension Command that builds a project.
    /// </summary>
    [DisplayName("Build Project")]
    [Description("Builds a Project")]
    [Category("IDE")]
    public class BuildProject : FeatureCommand
    {
        /// <summary>
        /// Gets the ServiceProvider that we will use to get a reference to DTE.
        /// </summary>
        [Import(typeof(SVsServiceProvider))]
        public IServiceProvider ServiceProvider { get; private set; }

        #region Overrides

        public override void Execute()
        {
            try
            {
                // Changed this from SolutionBuild.BuildProject because that call, despite
                // what the VS.NET documentation states, does not always build the
                // dependent assemblies first, thereby causing compilation errors.
                DTE dte = this.ServiceProvider.GetService(typeof(DTE)) as DTE;
                dte.DTE.ExecuteCommand("Build.BuildSelection", String.Empty);

                // The command is executed asynchronously, wait until the build is done
                while (dte.DTE.Solution.SolutionBuild.BuildState != vsBuildState.vsBuildStateDone)
                {
                    System.Windows.Forms.Application.DoEvents();
                }

                if (dte.DTE.Solution.SolutionBuild.LastBuildInfo != 0)
                {
                    ((EnvDTE80.DTE2)dte.DTE).ToolWindows.ErrorList.Parent.Activate();
                }
            }
            catch
            {
            }
        }

        #endregion
    }
}
